<template>
  <div class="user-management">
    <el-card shadow="never">
      <!-- 顶部工具条 -->
      <div class="toolbar">
        <div class="toolbar-left">
          <el-input
            v-model="query.keyword"
            placeholder="搜索用户名 / 邮箱"
            style="width:220px"
            clearable
            @keyup.enter="handleSearch"
          />
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="primary" @click="openAdd">新增用户</el-button>
        </div>

        <!-- 右侧用户信息和退出登录 -->
        <div class="toolbar-right">
          <span class="user-welcome">👋 欢迎，{{ getCurrentUser() }}</span>
          <el-button type="danger" plain @click="logout">🚪 退出登录</el-button>
        </div>
      </div>

      <!-- 调试信息 -->
      <div class="debug-info">
        总数: {{ total }} | 当前页: {{ query.page }} | 关键词: "{{ query.keyword }}"
      </div>

      <!-- 表格 -->
      <el-table :data="tableData" v-loading="loading" border>
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="deptName" label="部门" />
        <el-table-column prop="status" label="状态" width="90">
          <template #default="{ row }">
            <el-tag :type="row.status === 'ACTIVE' ? 'success' : 'info'">
              {{ row.status === 'ACTIVE' ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="170" />
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="openEdit(row)">
              编辑
            </el-button>
            <el-button type="text" size="small" style="color:red" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-if="total > 0"
        background
        layout="prev, pager, next"
        :current-page="query.page"
        :page-size="query.size"
        :total="total"
        class="pagination"
        @current-change="handlePageChange"
      />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="520px">
      <el-form ref="formRef" :model="formModel" :rules="rules" label-width="80px">
        <el-form-item prop="username" label="用户名">
          <el-input v-model="formModel.username" />
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="formModel.email" />
        </el-form-item>
        <el-form-item v-if="isAdd" prop="password" label="密码">
          <el-input v-model="formModel.password" type="password" show-password />
        </el-form-item>
        <el-form-item label="角色">
          <el-select
            v-model="formModel.roleId"
            placeholder="请选择角色"
            style="width: 100%"
            clearable
          >
            <el-option
              v-for="r in roleOpts"
              :key="r.value"
              :label="r.label"
              :value="r.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="部门">
          <el-select
            v-model="formModel.deptId"
            placeholder="请选择部门"
            style="width: 100%"
            clearable
          >
            <el-option
              v-for="d in deptOpts"
              :key="d.value"
              :label="d.label"
              :value="d.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formModel.status">
            <el-radio value="ACTIVE">启用</el-radio>
            <el-radio value="INACTIVE">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { getUserList, addUser, updateUser, deleteUser, getRoleOptions, getDeptOptions, type User, type UserForm, type OptionItem } from '../../../api/user'

// 路由
const router = useRouter()

// 使用API文件中的类型定义

// 获取当前用户名
const getCurrentUser = () => {
  const userInfo = localStorage.getItem('userInfo')
  if (userInfo) {
    try {
      const user = JSON.parse(userInfo)
      return user.username || 'admin'
    } catch {
      return 'admin'
    }
  }
  return 'admin'
}

// 退出登录
const logout = () => {
  ElMessageBox.confirm('确定要退出登录吗？', '确认退出', {
    type: 'warning',
    confirmButtonText: '确定退出',
    cancelButtonText: '取消'
  }).then(() => {
    // 清除本地存储
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')

    ElMessage.success('退出登录成功')

    // 跳转到登录页
    setTimeout(() => {
      router.replace('/login')
    }, 1000)
  }).catch(() => {
    // 用户取消
  })
}

// 响应式数据
const tableData = ref<User[]>([])
const total = ref(0)
const loading = ref(false)
const query = reactive({ page: 1, size: 10, keyword: '' })

// 下拉选项
const roleOpts = ref<OptionItem[]>([])
const deptOpts = ref<OptionItem[]>([])

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('新增用户')
const formRef = ref<FormInstance>()
const isAdd = ref(true)

// 表单数据
const emptyForm: UserForm = {
  username: '',
  email: '',
  password: '',
  roleId: undefined,
  deptId: undefined,
  status: 'ACTIVE'
}
const formModel = reactive<UserForm>({ ...emptyForm })

// 表单验证规则
const rules: FormRules = {
  username: [{ required: true, message: '用户名必填', trigger: 'blur' }],
  email: [
    { required: true, message: '邮箱必填', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
  ],
  password: [{ required: true, message: '密码必填', trigger: 'blur' }]
}

// 获取角色和部门选项
const fetchOptions = async () => {
  try {
    console.log('🔍 开始获取角色和部门选项...')
    const [roleResponse, deptResponse] = await Promise.all([
      getRoleOptions(),
      getDeptOptions()
    ])

    console.log('🔍 角色响应:', roleResponse)
    console.log('🔍 部门响应:', deptResponse)

    // 详细检查角色数据
    console.log('🔍 角色数据详情:')
    if (roleResponse.data && Array.isArray(roleResponse.data)) {
      roleResponse.data.forEach((role, index) => {
        console.log(`  角色${index + 1}:`, {
          value: role.value,
          label: role.label,
          'value类型': typeof role.value,
          'label类型': typeof role.label,
          'value是否有效': role.value !== undefined && role.value !== null,
          'label是否有效': role.label !== undefined && role.label !== null
        })
      })
    } else {
      console.warn('⚠️ 角色数据不是数组:', roleResponse.data)
    }

    // 详细检查部门数据
    console.log('🔍 部门数据详情:')
    if (deptResponse.data && Array.isArray(deptResponse.data)) {
      deptResponse.data.forEach((dept, index) => {
        console.log(`  部门${index + 1}:`, {
          value: dept.value,
          label: dept.label,
          'value类型': typeof dept.value,
          'label类型': typeof dept.label,
          'value是否有效': dept.value !== undefined && dept.value !== null,
          'label是否有效': dept.label !== undefined && dept.label !== null
        })
      })
    } else {
      console.warn('⚠️ 部门数据不是数组:', deptResponse.data)
    }

    roleOpts.value = roleResponse.data || []
    deptOpts.value = deptResponse.data || []

    console.log('✅ 选项数据加载完成:', {
      roles: roleOpts.value.length,
      depts: deptOpts.value.length,
      roleData: roleOpts.value,
      deptData: deptOpts.value
    })

    // 最终检查设置后的数据
    console.log('🔍 最终角色选项检查:')
    roleOpts.value.forEach((role, index) => {
      console.log(`  最终角色${index + 1}:`, {
        value: role.value,
        label: role.label,
        'value类型': typeof role.value,
        'label类型': typeof role.label
      })
    })

    console.log('🔍 最终部门选项检查:')
    deptOpts.value.forEach((dept, index) => {
      console.log(`  最终部门${index + 1}:`, {
        value: dept.value,
        label: dept.label,
        'value类型': typeof dept.value,
        'label类型': typeof dept.label
      })
    })

  } catch (error) {
    console.error('❌ 获取选项数据失败:', error)
  }
}

// 业务逻辑方法
const fetchTable = async () => {
  loading.value = true
  try {
    const response = await getUserList()

    // 解析API返回的数据
    let rawData: any[] = []
    const responseData = response as any

    // 根据实际API返回格式解析数据
    if (responseData.data?.data?.list && Array.isArray(responseData.data.data.list)) {
      rawData = responseData.data.data.list
    } else if (responseData.data?.data && Array.isArray(responseData.data.data)) {
      rawData = responseData.data.data
    } else if (responseData.data && Array.isArray(responseData.data)) {
      rawData = responseData.data
    } else {
      console.warn('API数据格式异常，使用空数组')
      rawData = []
    }

    // 数据映射：后端字段名转前端字段名
    const mappedData: User[] = rawData.map((user: any) => {
      // 状态字段映射：后端可能返回boolean，前端使用字符串
      let status: 'ACTIVE' | 'INACTIVE' = 'ACTIVE'
      if (user.status === false || user.status === 'INACTIVE' || user.status === 0) {
        status = 'INACTIVE'
      } else if (user.status === true || user.status === 'ACTIVE' || user.status === 1) {
        status = 'ACTIVE'
      }

      return {
        id: user.id,
        username: user.userName || user.username || '', // 后端返回userName，前端使用username
        email: user.email || '',
        roleId: user.roleIds?.[0] || user.roleId,
        roleName: user.roleName || '',
        deptId: user.deptId,
        deptName: user.deptName || '',
        status: status,
        createTime: user.createTime || user.createTime || ''
      }
    })

    console.log('🔍 原始用户数据:', rawData)
    console.log('🔍 映射后用户数据:', mappedData)

    // 过滤和分页处理
    let filteredData = mappedData
    if (query.keyword) {
      filteredData = mappedData.filter(user =>
        (user.username || '').includes(query.keyword) ||
        (user.email || '').includes(query.keyword)
      )
    }

    const start = (query.page - 1) * query.size
    const end = start + query.size
    tableData.value = filteredData.slice(start, end)
    total.value = filteredData.length


  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
    tableData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

const openAdd = () => {
  Object.assign(formModel, { ...emptyForm })
  isAdd.value = true
  dialogTitle.value = '新增用户'
  dialogVisible.value = true
  formRef.value?.clearValidate()
}

const openEdit = (row: User) => {
  Object.assign(formModel, {
    id: row.id,
    username: row.username,
    email: row.email,
    password: '',
    roleId: row.roleId,
    deptId: row.deptId,
    status: row.status
  })
  isAdd.value = false
  dialogTitle.value = '编辑用户'
  dialogVisible.value = true
  formRef.value?.clearValidate()
}

const handleCancel = () => {
  dialogVisible.value = false
  formRef.value?.resetFields()
}

const handleSave = async () => {
  try {
    await formRef.value?.validate()

    if (isAdd.value) {
      await addUser(formModel)
      query.page = 1
    } else {
      const updateData = { ...formModel }
      if (!updateData.password) {
        delete updateData.password
      }
      await updateUser((formModel as any).id, updateData)
    }

    dialogVisible.value = false
    await fetchTable()
  } catch (error) {
    console.error('保存失败:', error)
    // API已经处理了错误消息，这里不需要重复显示
  }
}

const handleDelete = (row: User) => {
  ElMessageBox.confirm(`确定删除【${row.username}】？`, '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteUser(row.id)
      if (tableData.value.length === 1 && query.page > 1) {
        query.page--
      }
      await fetchTable()
    } catch (error) {
      console.error('删除失败:', error)
      // API已经处理了错误消息，这里不需要重复显示
    }
  }).catch(() => {})
}

const handleSearch = () => {
  query.page = 1
  fetchTable()
}

const handleReset = () => {
  query.keyword = ''
  query.page = 1
  fetchTable()
}

const handlePageChange = (page: number) => {
  query.page = page
  fetchTable()
}

// 初始化
onMounted(() => {
  fetchTable()
  fetchOptions()
})
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.toolbar {
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.toolbar-left {
  display: flex;
  gap: 8px;
  align-items: center;
  flex: 1;
}

.toolbar-right {
  display: flex;
  gap: 12px;
  align-items: center;
}

.user-welcome {
  color: #606266;
  font-size: 14px;
  font-weight: 500;
  background: #f0f9ff;
  padding: 8px 16px;
  border-radius: 6px;
  border: 1px solid #b3d8ff;
  white-space: nowrap;
}

.debug-info {
  font-size: 12px;
  color: #666;
  background: #f5f5f5;
  padding: 4px 8px;
  border-radius: 4px;
  margin-bottom: 16px;
}

.pagination {
  margin-top: 16px;
  justify-content: flex-end;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
    align-items: stretch;
  }

  .toolbar-left {
    flex-direction: column;
    gap: 8px;
  }

  .toolbar-right {
    justify-content: center;
  }
}
</style>
